package com.fun.demo.fun.kayang;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

//模拟Telnet测试连接耗时
public class TelnetTimeTracker {

    public static void main(String[] args) {
        String host = "172.18.3.212"; // 替换为你的数据库IP
        int port = 54321;              // 替换为你的数据库端口
        int intervalMs = 1000;         // 测试间隔(毫秒)
        String logFile = "D:/java_telnet_timings.log"; // 日志文件

        // 循环测试
        while (true) {
            long duration = testConnection(host, port);
            logResult(host, port, duration, logFile);

            try {
                Thread.sleep(intervalMs);
            } catch (InterruptedException e) {
                System.out.println("程序被中断");
                break;
            }
        }
    }

    /**
     * 测试TCP连接耗时
     * @return 连接耗时(毫秒)
     */
    private static long testConnection(String host, int port) {
        long startTime = System.currentTimeMillis();

        // 使用try-with-resources确保socket正确关闭
        try (Socket socket = new Socket()) {
            // 设置连接超时，避免长时间阻塞
            socket.connect(new InetSocketAddress(host, port), 5000);
            long endTime = System.currentTimeMillis();
            return endTime - startTime;

        } catch (IOException e) {
            long endTime = System.currentTimeMillis();
            System.err.println("连接失败: " + e.getMessage() + "，耗时: " + (endTime - startTime) + "ms");
            return -1; // 用-1表示连接失败
        }
    }

    /**
     * 记录结果到文件和控制台
     */
    private static void logResult(String host, int port, long durationMs, String logFile) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String message = String.format("%s - Telnet to %s:%d took: %d ms",
                timestamp, host, port, durationMs);

        // 输出到控制台
        System.out.println(message);

        // 输出到文件
        try (java.io.FileWriter fw = new java.io.FileWriter(logFile, true);
             java.io.PrintWriter pw = new java.io.PrintWriter(fw)) {
            pw.println(message);
        } catch (IOException e) {
            System.err.println("写入日志文件失败: " + e.getMessage());
        }
    }
}
